<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 后台通用方法
class Hzy extends BaseController {

	public function __construct() {
        parent::__construct();
    }

    // 单点登录
    public function sso(){
        // 加载db类
        $this->load->model('schoolModel');
        $this->load->model('staffModel');
        $this->load->model('accountModel');
        $this->load->model('classesModel');
        // 加载类库
        $this->load->library("haozhuanyeV2");

        $ticket = $this->get("ticket");
        if(!$ticket) throw new Exception("参数错误");
        // 是否调试
        $debug = $this->get("debug");
        // 请求接口
        $result = $this->haozhuanyev2->check_hzy_ticket($ticket);
        $result = json_decode($result, true);
        // print_r($result);exit;

        if($result['code'] != 0) throw new Exception($result['message']);
        if($result['result']['code'] != 0) throw new Exception($result['result']['message']);
        // 去掉残存的session
        if($this->session->intensiveModule){
            $this->session->set_userdata("intensiveModule", NULL);
        }

        // 获取用户信息
        $userInfo = $result['result']['userInfo'];
        if($debug) {
            print_r($userInfo);exit;
        }
        // 获取学校信息
        $schoolInfo = $this->schoolModel->get_school_info_by_x_id($userInfo['schoolID']);
        if(!$schoolInfo) throw new Exception("当前学校不存在，请在数据同步后重试");

        // 获取教师信息
        $teacherInfo = $this->schoolModel->get_teacher_info_by_username($userInfo['userName'], $schoolInfo['id']);
        if(!$teacherInfo) throw new Exception("不存在的教师角色，请在数据同步后重试");

        // // 测试
        // $schoolInfo = $this->schoolModel->get_school_info_by_x_id(3597);
        // 获取教师信息
        // $teacherInfo = $this->schoolModel->get_teacher_info_by_username('20160155', $schoolInfo['id']);  // 班主任
        // $teacherInfo = $this->schoolModel->get_teacher_info_by_username('20180686', $schoolInfo['id']);      // 年级管理员
        // $teacherInfo = $this->schoolModel->get_teacher_info_by_username('test', $schoolInfo['id']);      // 后台管理员
        // $teacherInfo = $this->schoolModel->get_teacher_info_by_username('ceshi', $schoolInfo['id']);      // 学校管理员
        // echo '<pre>';var_export($teacherInfo);exit;

   
        // 获取校区
        $params['schoolId'] = $schoolInfo['id'];
        $params['isDelete'] = 0;
        $campusList = $this->schoolModel->get_campus_list($params);
        $campusInfo = $campusList[0];
        // 保存学校信息
        $teacherInfo['school'] = $schoolInfo;

        // 保存教师登录状态。改动登录逻辑的话，需要连后台登录的代码也一起改
        // 判断是否携带module参数
        if(empty($this->get('module'))){
            // 没携带module参数就按照原来权限逻辑
            $menuIdSet = $this->staffModel->get_menu_id_by_role_id($teacherInfo['role_id_set']);
            // 根据用户类型，获取后台菜单列表
            $roleData = $this->accountModel->get_admin_menu($teacherInfo['user_type'], $menuIdSet);
            $teacherInfo['roleMenu'] = $roleData['roleMenu'];
            $teacherInfo['roleArray'] = $roleData['roleArray'];
            // 改成执教关系
            if($teacherInfo['user_type'] == USER_TYPE_TEACHER) {
                // 获取班级列表
                $classParams['isDelete'] = 0;
                $classParams['schoolId'] = $teacherInfo['school_id'];
                $classList = $this->classesModel->get_class_list($classParams);
                // 使用id作为键
                $classList = array_value_to_key($classList, 'id');
                // 获取执教关系列表
                $coachParams['teacherId'] = $teacherInfo['id'];
                $coachList = $this->staffModel->get_coach_list($coachParams);
                // 通过coachList获取任课班级
                $teacherInfo['classIdArr'] = $this->getTeacherClassByCoachList($coachList, $teacherInfo['school_id'])['teacherClassIdArr'];
                $teacherInfo['classArr'] = $this->getTeacherClassByCoachList($coachList, $teacherInfo['school_id'])['teacherClassArr'];
                // 学校管理员classArr数据太长，存储session报错Failed to decode session object. Session has been destroyed
                // 将学校管理员的user_type设置为2，即为后台管理员
                if($this->checkIsSchoolAdminByCoachList($coachList)) {
                    $teacherInfo['user_type'] = USER_TYPE_SCHOOL;
                    $teacherInfo['classArr'] = array();
                }
                $teacherInfo['class_ids'] = count($teacherInfo['classIdArr']) > 1 ? implode(',', $teacherInfo['classIdArr']) : '-1';
            }
            // 登录成功，数据写入session
            $this->session->set_userdata("rmxUser", $teacherInfo);
            $this->session->set_userdata("campusList", $campusList);
            $this->session->set_userdata("campusInfo", $campusInfo);
            // 跳转到后台首页
            $redirectUrl = admin_url("home");

            redirect($redirectUrl);
        } else{
            // 如携带了module参数，就只获取对应的模块权限
            // 1.集约网站
            // 2.内部邮件
            // 3.申请审批
            // 4.班牌管理，包含内容管理,多媒体管理,人员结构管理和学校管理
            $module = $this->get('module');
            // $arr = array('cms', 'mail', 'workflow', 'brand', 'person', 'school', 'data', 'source');
            $arr = array('cms', 'mail', 'workflow', 'brand');
            if(!in_array($module, $arr)){
                throw new Exception('module参数不合法');
            }

            $menu = $this->accountModel->get_menu_by_url($module);
            $pid = '';
            if(!empty($menu)){
                $pid = $menu['id'];
            }
            $menuIdSet = $pid;
            // 根据父级id获取所有子id
            $childMenus = $this->accountModel->get_sub_menu_by_id($pid);
            foreach($childMenus as $childMenu){
                if($childMenu['id']) {
                    $menuIdSet .= ',' . $childMenu['id'];
                }
            }
            // 如moudle参数是brand,就多获取‘内容管理’和‘多媒体管理’
            if($module === 'brand'){
                // 获取‘内容管理’的menu_id
                $menuNameArray = array("contents", "teachers", "students", "data", "lessons");
                foreach($menuNameArray as $menuName) {
                    $menu = $this->accountModel->get_menu_by_url($menuName);
                    $pid = $menu['id'];
                    if($pid) {
                        $menuIdSet .= ',' . $pid;
                    }
                    // 获取子菜单
                    $childMenus = $this->accountModel->get_sub_menu_by_id($pid);
                    foreach($childMenus as $childMenu){
                        if($childMenu['id']) {
                            $menuIdSet .= ',' . $childMenu['id'];
                        }
                    }
                }
            }

            $roleData = $this->accountModel->get_admin_menu($teacherInfo['user_type'], $menuIdSet);
            $teacherInfo['roleMenu'] = $roleData['roleMenu'];
            $teacherInfo['roleArray'] = $roleData['roleArray'];
            // // 设置用户类型为学校管理员
            // $teacherInfo['user_type'] = USER_TYPE_SCHOOL;
            // 改成执教关系
            if($teacherInfo['user_type'] == USER_TYPE_TEACHER) {
                // 获取班级列表
                $classParams['isDelete'] = 0;
                $classParams['schoolId'] = $teacherInfo['school_id'];
                $classList = $this->classesModel->get_class_list($classParams);
                // 使用id作为键
                $classList = array_value_to_key($classList, 'id');
                // 获取执教关系列表
                $coachParams['teacherId'] = $teacherInfo['id'];
                $coachList = $this->staffModel->get_coach_list($coachParams);
                // 通过coachList获取任课班级
                $teacherInfo['classIdArr'] = $this->getTeacherClassByCoachList($coachList, $teacherInfo['school_id'])['teacherClassIdArr'];
                $teacherInfo['classArr'] = $this->getTeacherClassByCoachList($coachList, $teacherInfo['school_id'])['teacherClassArr'];
                // 学校管理员classArr数据太长，存储session报错Failed to decode session object. Session has been destroyed
                // 将学校管理员的user_type设置为2，即为后台管理员
                if($this->checkIsSchoolAdminByCoachList($coachList)) {
                    $teacherInfo['user_type'] = USER_TYPE_SCHOOL;
                    $teacherInfo['classArr'] = array();
                }
                $teacherInfo['class_ids'] = count($teacherInfo['classIdArr']) > 1 ? implode(',', $teacherInfo['classIdArr']) : '-1';
            }
            // echo '<pre>';var_export($teacherInfo);exit;
            // 登录成功，数据写入session
            $this->session->set_userdata("rmxUser", $teacherInfo);
            $this->session->set_userdata("campusList", $campusList);
            $this->session->set_userdata("campusInfo", $campusInfo);
            // session写入集约化模块标记
            $this->session->set_userdata("intensiveModule", $module);

            // 集约化网站，跳转到新ui界面
            if($module === 'cms') {
                redirect(admin_url('sub/cms/index'));
            }

            // 跳转到集约化网址首页
            redirect(admin_url(array_values($this->session->rmxUser['roleMenu'])[0]['sub'][0]['menu_url']));
        }
    }

    // 单点登录，企业微信
    public function wx_sso(){
        // 加载db类
        $this->load->model('schoolModel');
        $this->load->model('staffModel');
        $this->load->model('accountModel');
        $this->load->model('classesModel');
        // 加载类库
        $this->load->library("haozhuanyeV2");

        $ticket = $this->get("ticket");
        if(!$ticket) throw new Exception("参数错误");
        // 是否调试
        $debug = $this->get("debug");
        // 请求接口
        $result = $this->haozhuanyev2->check_hzy_wx_ticket($ticket);
        $result = json_decode($result, true);
        // print_r($result);exit;

        if($result['code'] != 0) throw new Exception($result['message']);
        if($result['result']['code'] != 0) throw new Exception($result['result']['message']);

        // 获取用户信息
        $userInfo = $result['result']['userInfo'];
        if($debug) {
            print_r($userInfo);exit;
        }
        // 获取学校信息
        $schoolInfo = $this->schoolModel->get_school_info_by_x_id($userInfo['schoolID']);
        if(!$schoolInfo) throw new Exception("当前学校不存在，请在数据同步后重试");

        // 获取教师信息
        $teacherInfo = $this->schoolModel->get_teacher_info_by_username($userInfo['userName'], $schoolInfo['id']);
        if(!$teacherInfo) throw new Exception("不存在的教师角色，请在数据同步后重试");

        // // 测试
        // $schoolInfo = $this->schoolModel->get_school_info_by_x_id(3597);
        // 获取教师信息
        // $teacherInfo = $this->schoolModel->get_teacher_info_by_username('20160155', $schoolInfo['id']);  // 班主任
        // $teacherInfo = $this->schoolModel->get_teacher_info_by_username('20180686', $schoolInfo['id']);      // 年级管理员
        // $teacherInfo = $this->schoolModel->get_teacher_info_by_username('test', $schoolInfo['id']);      // 后台管理员
        // $teacherInfo = $this->schoolModel->get_teacher_info_by_username('ceshi', $schoolInfo['id']);      // 学校管理员
        // echo '<pre>';var_export($teacherInfo);exit;

   
        // // 获取校区
        // $params['schoolId'] = $schoolInfo['id'];
        // $params['isDelete'] = 0;
        // $campusList = $this->schoolModel->get_campus_list($params);
        // $campusInfo = $campusList[0];
        // // 保存学校信息
        // $teacherInfo['school'] = $schoolInfo;

        // // 登录成功，数据写入session
        // $this->session->set_userdata("rmxUser", $teacherInfo);
        // $this->session->set_userdata("campusList", $campusList);
        // $this->session->set_userdata("campusInfo", $campusInfo);

        $sessArr = array(
            'qywx' => true,
            // 'openid' => '',
            'user' => $teacherInfo,
            'bind_user_type' => BIND_TYPE_TEACHER
        );
        $this->session->set_userdata('wx', $sessArr);

        // 跳转到手机端个人中心
        $redirectUrl = wx_url("user/index");

        redirect($redirectUrl);
    }

    // 班牌单点登录，提供给校验我们的ticket
    public function ssoLogin() {
        // 加载db类
        $this->load->model('schoolModel');
        $ticket = $this->get('ticket');
        // 获取学生信息
        $studentInfo = $this->schoolModel->get_student_info_by_ticket($ticket);
        if(empty($studentInfo)) {
            $data = array(
                'code' => 1,
                'status' => 'fail',
                'result' => array(
                    'code' => 1,
                    'userInfo' => NULL,
                    'message' => 'ticket不存在或者已失效'
                )
            );
            exit(json_encode($data, JSON_UNESCAPED_UNICODE));
        }
        // 获取学生学校
        $schoolInfo = $this->schoolModel->get_school_info($studentInfo['school_id']);
        $userInfo = array(
            'studentEID' => $studentInfo['x_student_id'],
            'schoolEID' => $schoolInfo['school_x_id']
        );
        $data = array(
            'code' => 0,
            'status' => 'success',
            'result' => array(
                'code' => 0,
                'userInfo' => $userInfo,
                'message' => '验证成功'
            )
        );
        // // 验证成功，清除ticket(班牌端得先请求一次判断status，共得请求两次，故不能清除)
        // $this->db->update(SchoolModel::$schoolStudentTable, array(
        //     'ticket' => '',
        //     'updatetime' => date('Y-m-d H:i:s')
        // ), array(
        //     'id' => $studentInfo['id']
        // ));

        exit(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    // 提交考勤数据
    public function post_sign_data(){
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 加载类库
        $this->load->library("haozhuanyeV2");

        // 获取数据
        $data['pageStart'] = 0;
        $data['pageSize'] = 1;
        $data['isSubmit'] = 1;
        $signData = $this->classesModel->get_sign_data($data);
        // echo '<pre>';var_export($signData);exit;
        if($signData) {

            // 获取学校ID
            $schoolId = $signData[0]['school_id'];
            $data['pageSize'] = 20; // 将每次提交数据改为20条
            $data['schoolId'] = $schoolId;
            $signDataList = $this->classesModel->get_sign_data($data);


            // 提交数据到
            $schoolInfo = $this->schoolModel->get_school_info($schoolId);
            $postData['schoolID'] = $schoolInfo['school_x_id'];
            $postData['login'] = $schoolInfo['school_x_params'];
            $postData['token'] = $schoolInfo['school_x_token'];
            // $postData['serial'] = time();
            $postData = $this->haozhuanyev2->get_post_data($postData['schoolID']);
            $postData['serial'] = time();
            $postData['data'] = array();

            // 签到数据
            $signDataArray = $studentArray = $classArray = $brandArray = $locationArray = $courseArray = array();

            foreach($signDataList as $signData) {
                // 获取学生信息
                $studentId = $signData['student_id'];
                if(isset($studentArray[$studentId])) {
                    $studentInfo = $studentArray[$studentId];
                } else {
                    $studentInfo = $this->schoolModel->get_student_info($studentId);
                    // 保存学生数据到数组
                    $studentArray[$studentId] = $studentInfo;
                }

                // 获取班级信息
                $classId = $signData['class_id'];
                if(isset($classArray[$classId])) {
                    $classInfo = $classArray[$classId];
                } else {
                    $classInfo = $this->classesModel->get_class_info($classId);
                    // 保存学生数据到数组
                    $classArray[$classId] = $classInfo;
                }

                // // 获取班牌信息
                // $brandId = $signData['brand_id'];
                // if(isset($brandArray[$brandId])) {
                //     $brandInfo = $brandArray[$brandId];
                // } else {
                //     $brandInfo = $this->classesModel->get_brand_info($brandId);
                //     // 保存学生数据到数组
                //     $brandArray[$brandId] = $brandInfo;
                // }

                // 获取课程信息
                $courseId = $signData['course_id'];
                if(isset($courseArray[$courseId])) {
                    $courseInfo = $courseArray[$courseId];
                } else {
                    $courseInfo = $this->classesModel->get_sch_lesson($courseId);
                    // 保存学生数据到数组
                    $courseArray[$courseId] = $courseInfo;
                }

                // 获取位置信息
                $locationId = $courseInfo['schedule_room_id'];
                if(isset($locationArray[$locationId])) {
                    $locationInfo = $locationArray[$locationId];
                } else {
                    $locationInfo = $this->classesModel->get_classroom_info($locationId);
                    // 保存学生数据到数组
                    $locationArray[$locationId] = $locationInfo;
                }

                $sd['id'] = $signData['id'];
                $sd['checkingTime'] = date("Y-m-d\TH:i:s.000\Z", strtotime($signData['createtime']. "-8 hours"));
                $sd['checkingStatus'] = '签到';
                $sd['studentEID'] = $studentInfo['x_student_id'];
                $sd['studentName'] = $studentInfo['realname'];
                $sd['classFullName'] = $classInfo['class_name'];
                $sd['classType'] = $classInfo['class_type'] == CLASSES_TYPE_NORMAL ? '行政班' : '教学班';
                $sd['cardID'] = $signData['student_card_number'];
                $sd['locationID'] = $locationInfo['x_classroom_id'];
                $sd['locationName'] = $locationInfo['classroom_name'];
                $sd['deviceID'] = "";
                // 获取图片base64内容
                if($signData['sign_img']) {
                    $imageInfo = getimagesize($signData['sign_img']);
                    $base64Image = "data:{$imageInfo['mime']};base64," . chunk_split(base64_encode(file_get_contents($signData['sign_img'])));
                } else {
                    $base64Image = "";
                }
                $sd['picData'] = $base64Image;

                $postData['data'][] = $sd;
            }

            // 提交数据到接口
            $postResult = $this->haozhuanyev2->post_sign_data($postData);
            if($postResult['status'] == 'success') {
                // 获取成功的数据
                $successDataId = array_value_implode($signDataList, "id");
                $updateData['sign_is_submit'] = 0;
                $this->db->update(ClassesModel::$signTable, $updateData, "id IN ({$successDataId})");
            }

            echo '<pre>';var_export($postResult);exit;
        }
    }


    // 同步学校数据
    public function update_hzy_school($schoolId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        $this->load->model('staffModel');
        // 加载类库
        $this->load->library("haozhuanyeV2");

        $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        if($schoolInfo['school_from'] != X_DATA_HAOZHUANYE) throw new Exception("该学校不是来自系统，数据同步失败");

        // 获取校区,默认更新第一个校区的数据（因为接口还没有返回校区列表）
        $params['schoolId'] = $schoolInfo['id'];
        $params['isDelete'] = 0;
        $campusList = $this->schoolModel->get_campus_list($params);
        $campusInfo = $campusList[0];
        // 初始化教师角色：任课教师，班主任，年级管理员，学校管理员
        $this->_update_hzy_teacher_role_data($schoolInfo);
        // 同步老师数据
        $this->_update_hzy_teacher_data($schoolInfo);
        // 同步科目列表
        $this->_update_hzy_lesson_data($schoolInfo);
        // 同步教室位置接口
        $this->_update_hzy_classroom_data($schoolInfo, $campusInfo);
        // 同步年级数据接口
        $this->_update_hzy_grade_data($schoolInfo, $campusInfo);
        // 同步班级接口
        $this->_update_hzy_class_data($schoolInfo, $campusInfo);
        // 同步学生接口
        $this->_update_hzy_student_data($schoolInfo, $campusInfo);
        // 同步课表
        $this->_update_hzy_schedule_data($schoolInfo, $campusInfo);
        // 同步考试数据
        $this->_update_hzy_exam_data($schoolInfo, $campusInfo);
        // 同步班主任执教关系数据
        $this->_update_hzy_coach_master_data($schoolInfo, $campusInfo);
        // 同步年级管理员执教关系数据
        $this->_update_hzy_coach_grade_admin_data($schoolInfo, $campusInfo);
        // 同步学校管理员执教关系数据
        $this->_update_hzy_coach_school_admin_data($schoolInfo, $campusInfo);
        // 同步任课教师执教关系数据
        $this->_update_hzy_coach_teacher_data($schoolInfo, $campusInfo);
        // 把教师角色为空的设置‘任课教师’角色
        $this->_update_hzy_coach_teacher_role_empty_data($schoolInfo);

        // 更新时间
        $update['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(SchoolModel::$schoolTable, $update, "id='{$schoolId}'");
        exit(json("同步数据成功", true));
    }
    // 初始化教师角色数据：任课教师，班主任，年级管理员，学校管理员
    private function _update_hzy_teacher_role_data($schoolInfo) {
        // 获取学校角色数据
        $roleList = $this->staffModel->get_role_list($schoolInfo['id']);
        // 将role_name作为键值
        $roleList = array_value_to_key_with_underline($roleList, 'role_name');
        $insertDataArr = array();
        if(!isset($roleList['任课教师'])) {
            $saveData['school_id'] = $schoolInfo['id'];
            $saveData['role_name'] = '任课教师';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '0,89,90,91,92,94,104,106,107,108,109,110,111,112,113,114,118,119';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if(!isset($roleList['班主任'])) {
            $saveData['school_id'] = $schoolInfo['id'];
            $saveData['role_name'] = '班主任';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '0,89,90,91,92,94,104,106,107,108,109,110,111,112,113,114,118,119';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if(!isset($roleList['年级管理员'])) {
            $saveData['school_id'] = $schoolInfo['id'];
            $saveData['role_name'] = '年级管理员';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '0,89,90,91,92,94,104,106,107,108,109,110,111,112,113,114,118,119';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if(!isset($roleList['学校管理员'])) {
            $saveData['school_id'] = $schoolInfo['id'];
            $saveData['role_name'] = '学校管理员';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '89,90,91,92,93,94,95,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,147,156';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if($insertDataArr) {
            // 插入
            $this->db->insert_batch(StaffModel::$roleTable, $insertDataArr);
        }
    }
    // 同步老师数据
    private function _update_hzy_teacher_data($schoolInfo) {
        // 获取教师列表
        $result = $this->haozhuanyev2->get_school_teacher($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage']);
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(SchoolModel::$schoolUserTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `user_type`=". USER_TYPE_TEACHER);
        $apiData = $result['result']['teachers'];
        // 获取本校全部老师
        $params['schoolId'] = $schoolInfo['id'];
        $teacherList = $this->schoolModel->get_teacher_list($params);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');
        // 获取接口所有教师列表
        $insertTeacherBatch = $updateTeacherBatch = array();
        $defaultPwd = password_hash(123456, PASSWORD_DEFAULT);
        foreach($apiData as $item) {
            $teacherId = $item['teacherEID'];
            // 入库
            $teacherData['school_id'] = $schoolInfo['id'];
            $teacherData['user_type'] = USER_TYPE_TEACHER;
            $teacherData['x_teacher_id'] = $teacherId;
            //自己做一个唯一ID
            $teacherData['x_unique_id'] = $schoolInfo['id']. "_". $teacherId;
            $teacherData['realname'] = $item['teacherName'];

            $teacherData['username'] = $teacherId;
            $teacherData['is_delete'] = 0;
            $teacherData['updatetime'] = date("Y-m-d H:i:s");

            // 更新还是新增
            if(isset($teacherList[$teacherId])) {
                $updateTeacherBatch[] = $teacherData;
            } else {
                $teacherData['password'] = $defaultPwd;
                $teacherData['createtime'] = $teacherData['updatetime'];
                $teacherData['headimgurl'] = UP_URL. "default/woman.jpg";
                $insertTeacherBatch[] = $teacherData;
            }
        }

        if(count($insertTeacherBatch)) $this->db->insert_batch(SchoolModel::$schoolUserTable, $insertTeacherBatch);
        if(count($updateTeacherBatch)) $this->db->update_batch(SchoolModel::$schoolUserTable, $updateTeacherBatch, "x_unique_id");
        // // 解决教师数据存在，而x_unique_id是空的情况
        // foreach($updateTeacherBatch as $updateTeacher) {
        //     if($updateTeacher['x_unique_id']) {
        //         $this->db->update(SchoolModel::$schoolUserTable, $updateTeacher, array('x_unique_id' => $updateTeacher['x_unique_id']));
        //     } else {
        //         $this->db->update(SchoolModel::$schoolUserTable, $updateTeacher, array('x_teacher_id' => $updateTeacher['x_teacher_id']));
        //     }
        // }
    }
    // 同步科目数据
    private function _update_hzy_lesson_data($schoolInfo) {
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(SchoolModel::$schoolLessonTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");

        // 获取接口数据
        $result = $this->haozhuanyev2->get_school_lesson($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取科目接口失败');
        $apiData = $result['result'];
        // 获取本校全部科目
        $lessonParams['schoolId'] = $schoolInfo['id'];
        $lessonList = $this->schoolModel->get_lesson_list($lessonParams);
        $lessonList = array_value_to_key($lessonList, 'x_lesson_id');
        // 获取接口所有科目列表
        $insertLessonBatch = $updateLessonBatch = array();
        foreach($apiData as $item) {
            $lessonData['school_id'] = $schoolInfo['id'];
            $lessonData['x_lesson_id'] = $item['id'];
            // 自己做一个唯一ID
            $lessonData['x_unique_id'] = $schoolInfo['id']. "_". $item['id'];
            $lessonData['lesson_name'] = $item['name'];
            $lessonData['lesson_short_name'] = $item['subjectShortName'];
            $lessonData['is_delete'] = 0;
            $lessonData['updatetime'] = date("Y-m-d H:i:s");
            // 更新还是新增
            if(isset($lessonList[$item['id']])) {
                $updateLessonBatch[] = $lessonData;
            } else {
                $lessonData['createtime'] = $lessonData['updatetime'];
                $insertLessonBatch[] = $lessonData;
            }
        }
        if(count($insertLessonBatch)) $this->db->insert_batch(SchoolModel::$schoolLessonTable, $insertLessonBatch);
        if(count($updateLessonBatch)) $this->db->update_batch(SchoolModel::$schoolLessonTable, $updateLessonBatch, "x_unique_id");
    }
    // 同步课室数据
    private function _update_hzy_classroom_data($schoolInfo, $campusInfo) {
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$classroomTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");

        // 获取接口数据
        $result = $this->haozhuanyev2->get_school_classroom($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取课室接口失败');
        $apiData = $result['result']['locations'];
        // 获取本校全部课室
        $roomParams['schoolId'] = $schoolInfo['id'];
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'x_classroom_id');
        // 遍历接口所有数据
        $insertRoomBatch = $updateRoomBatch = array();
        foreach($apiData as $item) {
            $locationsId = $item['locationID'];
            if(!$locationsId || $locationsId == 'null') continue;

            $roomData['school_id'] = $schoolInfo['id'];
            $roomData['x_classroom_id'] = $locationsId;
            $roomData['campus_id'] = $campusInfo['id'];             // 设置校区ID
            // 自己做一个唯一ID
            $roomData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $locationsId;
            $roomData['classroom_name'] = $item['locationName'];
            $roomData['is_delete'] = 0;
            $roomData['updatetime'] = date("Y-m-d H:i:s");
            // 更新还是新增
            if(isset($roomList[$locationsId])) {
                $updateRoomBatch[] = $roomData;
            } else {
                $roomData['createtime'] = $roomData['updatetime'];
                $insertRoomBatch[] = $roomData;
            }
        }
        if(count($insertRoomBatch)) $this->db->insert_batch(ClassesModel::$classroomTable, $insertRoomBatch);
        if(count($updateRoomBatch)) $this->db->update_batch(ClassesModel::$classroomTable, $updateRoomBatch, "x_unique_id");
    }
    // 同步年级接口（已废弃）
    private function _update_hzy_grade_data_old($schoolInfo, $campusInfo) {
        // 将全部数据设置为已删除状态，排序选修班年级
        $deleteState['is_delete'] = 1;
        $typeNormal = GRADE_TYPE_NORMAL;
        $this->db->update(ClassesModel::$gradeTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `grade_type` = {$typeNormal}");
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolInfo['id'];
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'x_grade_id');
        //获取全部行政班信息接口
        $insertGradeBatch = $updateGradeBatch = array();
        $result = $this->haozhuanyev2->get_school_classes($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取年级接口失败');
        $apiData = $result['result']['classes'];
        foreach($apiData as $item) {
            $gradeId = $item['gradeID'];
            // 设置年级数组
            $gradeData['school_id'] = $schoolInfo['id'];
            $gradeData['x_grade_id'] = $gradeId;
            $gradeData['campus_id'] = $campusInfo['id'];        // 设置校区id
            // 自己做一个唯一ID
            $gradeData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $gradeId;
            $gradeData['grade_name'] = $item['gradeName'];
            $gradeData['is_delete'] = 0;
            $gradeData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($gradeList[$gradeId])) {
                $updateGradeBatch[$gradeId] = $gradeData;
            } else {
                $gradeData['createtime'] = $gradeData['updatetime'];
                $insertGradeBatch[$gradeId] = $gradeData;
            }
        }
        // 获取全部教学班信息接口
        $result = $this->haozhuanyev2->get_school_teaching_classes($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取教学班接口失败');
        $apiData = $result['result']['teachingClasses'];
        foreach($apiData as $item) {
            $gradeId = $item['gradeID'];
            // 设置年级数组
            $gradeData['school_id'] = $schoolInfo['id'];
            $gradeData['x_grade_id'] = $gradeId;
            $gradeData['campus_id'] = $campusInfo['id'];        // 设置校区id
            // 自己做一个唯一ID
            $gradeData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $gradeId;
            $gradeData['grade_name'] = $item['gradeName'];
            $gradeData['is_delete'] = 0;
            $gradeData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($gradeList[$gradeId])) {
                $updateGradeBatch[$gradeId] = $gradeData;
            } else {
                $gradeData['createtime'] = $gradeData['updatetime'];
                $insertGradeBatch[$gradeId] = $gradeData;
            }
        }
        if(count($insertGradeBatch)) $this->db->insert_batch(ClassesModel::$gradeTable, $insertGradeBatch);
        if(count($updateGradeBatch)) $this->db->update_batch(ClassesModel::$gradeTable, $updateGradeBatch, "x_unique_id");
    }
    // 同步年级接口
    private function _update_hzy_grade_data($schoolInfo, $campusInfo) {
        // 将全部数据设置为已删除状态，排序选修班年级
        $deleteState['is_delete'] = 1;
        $typeNormal = GRADE_TYPE_NORMAL;
        $this->db->update(ClassesModel::$gradeTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `grade_type` = {$typeNormal}");
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolInfo['id'];
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'x_grade_id');
        //获取全部年级信息接口
        $insertGradeBatch = $updateGradeBatch = array();
        $result = $this->haozhuanyev2->get_school_grades($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取年级接口失败');
        $apiData = $result['result']['grades'];
        foreach($apiData as $item) {
            $gradeId = $item['gradeID'];
            // 设置年级数组
            $gradeData['school_id'] = $schoolInfo['id'];
            $gradeData['x_grade_id'] = $gradeId;
            $gradeData['campus_id'] = $campusInfo['id'];        // 设置校区id
            // 自己做一个唯一ID
            $gradeData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $gradeId;
            $gradeData['grade_name'] = $item['gradeName'];
            $gradeData['is_delete'] = 0;
            $gradeData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($gradeList[$gradeId])) {
                $updateGradeBatch[$gradeId] = $gradeData;
            } else {
                $gradeData['createtime'] = $gradeData['updatetime'];
                $insertGradeBatch[$gradeId] = $gradeData;
            }
        }
     
        if(count($insertGradeBatch)) $this->db->insert_batch(ClassesModel::$gradeTable, $insertGradeBatch);
        if(count($updateGradeBatch)) $this->db->update_batch(ClassesModel::$gradeTable, $updateGradeBatch, "x_unique_id");
    }
    // 同步班级接口
    private function _update_hzy_class_data($schoolInfo, $campusInfo) {
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        // 排除‘功能课室’班级即‘x_class_id’为空
        $this->db->update(ClassesModel::$classTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `x_class_id` != ''");
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolInfo['id'];
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'x_grade_id');
        // 获取本校全部课室
        $roomParams['schoolId'] = $schoolInfo['id'];
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'x_classroom_id');
        // 获取本校全部老师
        $teacherParams['schoolId'] = $schoolInfo['id'];
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');
        // 获取本校全部班级,排除功能课室班级，避免清除掉了课室
        $classParams['schoolId'] = $schoolInfo['id'];
        $classParams['inFunctional'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'x_class_id');
        //获取全部行政班信息接口
        $insertClassBatch = $updateClassBatch = array();
        $result = $this->haozhuanyev2->get_school_classes($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取班级接口失败');
        $apiData = $result['result']['classes'];
        foreach($apiData as $item) {
            $classData['school_id'] = $schoolInfo['id'];
            $classData['campus_id'] = $campusInfo['id']; // 设置校区id
            $classData['grade_id'] = $gradeList[$item['gradeID']]['id'];
            $classData['x_class_id'] = $item['qualifiedClassID'];
            // 自己做一个唯一ID
            $classData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $item['qualifiedClassID'];
            $classData['classroom_id'] = $item['locationID'] && isset($roomList[$item['locationID']]) ? $roomList[$item['locationID']]['id'] : 0;
            $classData['class_name'] = $item['classFullName'];
            // 如果有班主任
            // $classData['class_master'] = (isset($item['classTeacher']) && $item['classTeacher'] && isset($item['classTeacher']['teacherEID']) && isset($teacherList[$item['classTeacher']['teacherEID']])) ? $teacherList[$item['classTeacher']['teacherEID']]['id'] : 0;
            $classData['class_type'] = CLASSES_TYPE_NORMAL;
            $classData['is_delete'] = 0;
            $classData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($classList[$item['qualifiedClassID']])) {
                $updateClassBatch[] = $classData;
            } else {
                $classData['createtime'] = $classData['updatetime'];
                $insertClassBatch[] = $classData;
            }
        }
        // 获取全部教学班接口
        $result = $this->haozhuanyev2->get_school_teaching_classes($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取教学班接口失败');
        $apiData = $result['result']['teachingClasses'];

        foreach($apiData as $item) {
            $teachClassData['school_id'] = $schoolInfo['id'];
            $teachClassData['campus_id'] = $campusInfo['id']; // 设置校区id
            $teachClassData['grade_id'] = $gradeList[$item['gradeID']]['id'];
            $teachClassData['x_class_id'] = $item['qualifiedClassID'];
            // 自己做一个唯一ID
            $teachClassData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $item['qualifiedClassID'];
            
            $teachClassData['classroom_id'] = isset($item['locationID']) ? $roomList[$item['locationID']]['id'] : 0;

            $teachClassData['class_name'] = $item['classFullName'];
            // 如果有班主任
            // $classData['class_master'] = isset($item['classTeacher']) && $item['classTeacher']  ? $teacherList[$item['classTeacher']['teacherEID']]['id'] : 0;
            $teachClassData['class_type'] = CLASSES_TYPE_TEACHING;
            $teachClassData['is_delete'] = 0;
            $teachClassData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($classList[$item['qualifiedClassID']])) {
                $updateClassBatch[] = $teachClassData;
            } else {
                $teachClassData['createtime'] = $teachClassData['updatetime'];
                $insertClassBatch[] = $teachClassData;
            }
        }
        // 获取全部选修班信息接口
        $result = $this->haozhuanyev2->get_school_elective_classes($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取选修班接口失败');
        $apiData = $result['result']['electiveClasses'];
        if(count($apiData)) {
            // 判断有没'选修班'年级，没有就插入
            $electiveGradeInfo = $this->classesModel->get_elective_grade_info_list($schoolInfo['id'], $campusInfo['id']);
            if($electiveGradeInfo) {
                $electiveGradeId = $electiveGradeInfo['id'];
            } else {
                $electiveGradeData['createtime'] = date("Y-m-d H:i:s");
                $electiveGradeData['updatetime'] = date("Y-m-d H:i:s");
                $electiveGradeData['school_id'] = $schoolInfo['id'];
                $electiveGradeData['campus_id'] = $campusInfo['id'];        // 设置校区id
                $electiveGradeData['grade_name'] = '选修班';
                $electiveGradeData['grade_type'] = GRADE_TYPE_ELECTIVE;
                $electiveGradeData['is_delete'] = 0;
                $this->db->insert(ClassesModel::$gradeTable, $electiveGradeData);
                $electiveGradeId = $this->db->insert_id();
            }
        }
        // echo '<pre>';var_export($electiveGradeId);exit;
        foreach($apiData as $item) {
            $eleClassData['school_id'] = $schoolInfo['id'];
            $eleClassData['campus_id'] = $campusInfo['id']; // 设置校区id
            // 选修班跨年级
            $eleClassData['grade_id'] = $electiveGradeId;
            $eleClassData['x_class_id'] = $item['qualifiedClassID'];
            // 自己做一个唯一ID
            $eleClassData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $item['qualifiedClassID'];
            $eleClassData['class_name'] = $item['classFullName'];
            // $classData['class_master'] = 0;
            $eleClassData['class_type'] = CLASSES_TYPE_ELECTIVE;
            // 课室id为0
            $eleClassData['classroom_id'] = 0;
            $eleClassData['is_delete'] = 0;
            $eleClassData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($classList[$item['qualifiedClassID']])) {
                $updateClassBatch[] = $eleClassData;
            } else {
                $eleClassData['createtime'] = $eleClassData['updatetime'];
                $insertClassBatch[] = $eleClassData;
            }
        }
        // echo '<pre>';var_export($insertClassBatch);exit;
        if(count($insertClassBatch)) $this->db->insert_batch(ClassesModel::$classTable, $insertClassBatch);
        if(count($updateClassBatch)) $this->db->update_batch(ClassesModel::$classTable, $updateClassBatch, "x_unique_id");
    }
    // 同步学生接口
    private function _update_hzy_student_data($schoolInfo, $campusInfo){
        $result = $this->haozhuanyev2->get_school_student($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取学生接口失败');
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $deleteState['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(SchoolModel::$schoolStudentTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
        
        // 获取本校全部学生
        $studentParams['schoolId'] = $schoolInfo['id'];
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'x_student_id');
        // 获取行政班
        $classParams['schoolId'] = $schoolInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'x_class_id');
        // 获取接口学生
        $insertStudentBatch = $updateStudentBatch = array();
        $apiData = $result['result']['studentInfos'];
        $defaultPwd = password_hash(123456, PASSWORD_DEFAULT);
        foreach($apiData as $item) {
            $studentData['is_delete'] = 0;
            $studentData['school_id'] = $schoolInfo['id'];
            $studentData['campus_id'] = $campusInfo['id'];      // 设置校区ID
            $studentData['x_student_id'] = $item['studentEID'];
            // 增加username,跟x_student_id一样
            $studentData['username'] = $item['studentEID'];
            // 将的物理卡号设置跟x_student_id一样
            // $studentData['realcard'] = $item['studentEID'];

            // 自己做一个唯一ID
            $studentData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $item['studentEID'];

            if(!isset($classList[$item['qualifiedClassID']])) {
                throw new Exception('学生所属班级：' . $item['qualifiedClassID'] . ' 不存在');
                // continue;
            }

            $studentData['class_id'] = $classList[$item['qualifiedClassID']]['id'];
            // 获取教学班班级id
            $teachClassIds = array();
            foreach($item['teachingClassFullIDs'] as $teachId) {
                if(isset($classList[$teachId])) {
                    $teachClassIds[] = $classList[$teachId]['id'];
                }
            }
            $studentData['teaching_class_id'] = implode(",", $teachClassIds);
            // 获取选修班班级id
            $electiveClassIds = array();
            foreach($item['electiveClassFullIDs'] as $electiveId) {
                if(isset($classList[$electiveId])) {
                    $electiveClassIds[] = $classList[$electiveId]['id'];
                }
            }
            $studentData['elective_class_id'] = implode(",", $electiveClassIds);
            $studentData['realname'] = $item['studentName'];
            $studentData['gender'] = $item['gender'] ? $item['gender'] : '男';
            
            $studentData['updatetime'] = date("Y-m-d H:i:s");

            if(isset($studentList[$item['studentEID']])) {
                $updateStudentBatch[] = $studentData;
            } else {
                $studentData['password'] = $defaultPwd;
                $studentData['createtime'] = $studentData['updatetime'];

                $studentData['headimgurl'] = $item['gender'] == '男' ? UP_URL. "default/boy.jpg" : UP_URL. "default/girl.jpg";
                
                $insertStudentBatch[] = $studentData;
            }
        }
        if(count($insertStudentBatch)) $this->db->insert_batch(SchoolModel::$schoolStudentTable, $insertStudentBatch);
        if(count($updateStudentBatch)) $this->db->update_batch(SchoolModel::$schoolStudentTable, $updateStudentBatch, "x_unique_id");

        // // 更新`realcard`为空的数据
        // $table = TABLE_PREFIX. SchoolModel::$schoolStudentTable;
        // $this->db->query("UPDATE `{$table}` SET `realcard` = `username` WHERE `school_id`='{$schoolInfo['id']}' AND `realcard` = ''");

        // // 解决学生数据存在，而x_unique_id是空的情况
        // foreach($updateStudentBatch as $updateStudent) {
        //     if($updateStudent['x_unique_id']) {
        //         $this->db->update(SchoolModel::$schoolStudentTable, $updateStudent, array('x_unique_id' => $updateStudent['x_unique_id']));
        //     } else {
        //         $this->db->update(SchoolModel::$schoolStudentTable, $updateStudent, array('x_student_id' => $updateStudent['x_student_id']));
        //     }
        // }
    }

    // 同步课表接口
    private function _update_hzy_schedule_data($schoolInfo, $campusInfo){
        // 本周课程表
        $thisResult = $this->haozhuanyev2->get_school_schedule($schoolInfo['school_x_id']);
        if(!isset($thisResult['status']) || $thisResult['status'] != 'success') throw new Exception($thisResult['errorMessage'] ? $thisResult['errorMessage'] : '获取课表接口失败');
        // // 下周课程表
        // $nextResult = $this->haozhuanyev2->get_school_next_schedule($schoolInfo['school_x_id']);
        // if($nextResult['status'] != 'success') throw new Exception($nextResult['errorMessage']);
        // 获取本校课程表
        $scheduleParams['schoolId'] = $schoolInfo['id'];
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        $scheduleList = array_value_to_key($scheduleList, 'school_id,schedule_this_week');
        // 更新本周课表数据
        $this->__update_schedule_data($schoolInfo, $campusInfo, $scheduleList, 1, $thisResult);
        // // 更新下周课表数据
        // $this->__update_schedule_data($schoolInfo, $campusInfo, $scheduleList, 0, $nextResult);

        // 多年级作息，又存在选修班的情况，添加该选修年级的作息时间（默认获取第一个作息）
        $this->_update_hzy_elective_grade_schedule_data($schoolInfo, $campusInfo);

        // 重新获取本校课程表
        $scheduleParams['schoolId'] = $schoolInfo['id'];
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        $scheduleList = array_value_to_key($scheduleList, 'school_id,schedule_this_week');
        // 获取老师列表
        $teacherParams['schoolId'] = $schoolInfo['id'];
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');
        // 获取班级列表
        $classParams['schoolId'] = $schoolInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'x_class_id');
        // 获取教室列表
        $roomParams['schoolId'] = $schoolInfo['id'];
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'x_classroom_id');
        // 获取课表科目列表
        $scheduleLessonParams['schoolId'] = $schoolInfo['id'];
        $scheduleLessonList = $this->classesModel->get_school_schedule_lesson_for_sync($scheduleLessonParams);
        $scheduleLessonList = array_value_to_key($scheduleLessonList, 'schedule_lesson_id');

        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$scheduleLessonTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `campus_id`='{$campusInfo['id']}'");

        // 更新本周课表课程内容
        $this->__update_schedule_lesson_data($schoolInfo, $campusInfo, $scheduleList, $scheduleLessonList, $teacherList, $classList, $roomList, 1, $thisResult['result']['schedule']);
        // // 更新下周课表课程内容
        // $this->__update_schedule_lesson_data($schoolInfo, $campusInfo, $scheduleList, $scheduleLessonList, $teacherList, $classList, $roomList, 0, $nextResult['result']['schedule']);
    }
    // 课表接口，更新课程表数据
    private function __update_schedule_data($schoolInfo, $campusInfo, $scheduleList, $isThisWeek, $scheduleData){
        if(empty($scheduleData['result']['timeSettings']['times']) && empty($scheduleData['result']['gradeTimeSettings'])) {
            throw new Exception('获取课表接口错误');
        }

        // 插入模板数据
        $thisWeekData['school_id'] = $schoolInfo['id'];
        $thisWeekData['campus_id'] = $campusInfo['id'];     // 设置校区ID
        $thisWeekData['schedule_title'] = $scheduleData['result']['semester'] ? $scheduleData['result']['semester'] : '';
        $thisWeekData['schedule_this_week'] = $isThisWeek;
        $thisWeekData['updatetime'] = date("Y-m-d H:i:s");
        // 获取时间点
        if($scheduleData['result']['timeSettings']) {
            $thisWeekData['schedule_week_days'] = $scheduleData['result']['timeSettings']['daysPerWeek'];
            $thisWeekData['schedule_morning_number'] = $scheduleData['result']['timeSettings']['morningLessons'];
            $thisWeekData['schedule_afternoon_number'] = $scheduleData['result']['timeSettings']['afternoonLessons'];
            $thisWeekData['schedule_early_morning_number'] = $scheduleData['result']['timeSettings']['earlyMorningLessons'];
            $thisWeekData['schedule_night_number'] = $scheduleData['result']['timeSettings']['nightLessons'];
        }
        // 全校统一作息
        if(!empty($scheduleData['result']['timeSettings']['times'])) {
            $weekKey = $schoolInfo['id']. $isThisWeek;
            $thisWeekData['grade_id'] = 0;
            // $thisWeekData['school_id'] = $schoolInfo['id'];
            // $thisWeekData['campus_id'] = $campusInfo['id'];     // 设置校区ID
            // $thisWeekData['schedule_title'] = $scheduleData['result']['semester'] ? $scheduleData['result']['semester'] : '';
            // $thisWeekData['schedule_this_week'] = $isThisWeek;
            // 获取时间点
            if($scheduleData['result']['timeSettings']) {
            //     $thisWeekData['schedule_week_days'] = $scheduleData['result']['timeSettings']['daysPerWeek'];
            //     $thisWeekData['schedule_morning_number'] = $scheduleData['result']['timeSettings']['morningLessons'];
            //     $thisWeekData['schedule_afternoon_number'] = $scheduleData['result']['timeSettings']['afternoonLessons'];
            //     $thisWeekData['schedule_early_morning_number'] = $scheduleData['result']['timeSettings']['earlyMorningLessons'];
            //     $thisWeekData['schedule_night_number'] = $scheduleData['result']['timeSettings']['nightLessons'];
                $thisWeekData['schedule_time_json'] = json_encode($scheduleData['result']['timeSettings']['times'], JSON_UNESCAPED_UNICODE);
            }
            // $thisWeekData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($scheduleList[$weekKey])) {
                // 保留原来的课前多少分钟考勤与是否重新考勤
                if($scheduleData['result']['timeSettings']) {
                    $oldScheduleArr = json_decode($scheduleList[$weekKey]['schedule_time_json'], true);
                    $newScheduleArr = json_decode($thisWeekData['schedule_time_json'], true);
                    // echo '<pre>';var_export($oldScheduleArr);var_export($newScheduleArr);exit;
                    if($oldScheduleArr) {
                        foreach($oldScheduleArr as $key => $value) {
                            if(isset($newScheduleArr[$key])) {
                                // 判断是否删除
                                if(isset($value['sign_interval'])) {
                                    $newScheduleArr[$key]['sign_interval'] = $value['sign_interval'];
                                }
                                if(isset($value['refresh'])) {
                                    $newScheduleArr[$key]['refresh'] = $value['refresh'];
                                }
                            }
                        }
                        $thisWeekData['schedule_time_json'] = json_encode($newScheduleArr, JSON_UNESCAPED_UNICODE);
                    }
                }
    
                $this->db->update(ClassesModel::$scheduleTable, $thisWeekData, "id='{$scheduleList[$weekKey]['id']}'");
            } else {
                $thisWeekData['createtime'] = $thisWeekData['updatetime'];
                $this->db->insert(ClassesModel::$scheduleTable, $thisWeekData);
            }
        } else {
            // 先删除旧模板数据
            // 将全部数据设置为已删除状态
            $deleteState['is_delete'] = 1;
            $this->db->update(ClassesModel::$scheduleTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
            // 获取本校全部年级
            $gradeParams['schoolId'] = $schoolInfo['id'];
            $gradeList = $this->classesModel->get_grade_list($gradeParams);
            $gradeList = array_value_to_key($gradeList, 'x_grade_id');
            // 获取本校课程表
            $scheduleParams['schoolId'] = $schoolInfo['id'];
            $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
            $scheduleList = array_value_to_key_with_underline($scheduleList, 'school_id,schedule_this_week,grade_id,week');

           // 年级不同作息
           $gradeTimeSettings = $scheduleData['result']['gradeTimeSettings'];
           foreach($gradeTimeSettings as $gradeTimeSetting) {
               // 年级id
               $gradeXidArr = $gradeTimeSetting['grades'];
               foreach($gradeXidArr as $gradeXid) {
                    if(isset($gradeList[$gradeXid])) {
                        $thisWeekData['is_delete'] = 0;
                        $thisWeekData['grade_id'] = $gradeList[$gradeXid]['id'];
                        // 每天的作息
                        $groupTimes = $gradeTimeSetting['groupTimes'];
                        foreach($groupTimes as $groupTime) {
                            // 星期几
                            $thisWeekData['week'] = implode(',', $groupTime['schoolDays']);
                            // 作息时间
                            $thisWeekData['schedule_time_json'] = json_encode($groupTime['times'], JSON_UNESCAPED_UNICODE);

                            $gradeAndWeekKey = $schoolInfo['id']. '_' . $isThisWeek . '_' . $thisWeekData['grade_id'] . '_' . $thisWeekData['week'];
                            if(isset($scheduleList[$gradeAndWeekKey])) {
                                // 保留原来的课前多少分钟考勤与是否重新考勤
                                $oldScheduleArr = json_decode($scheduleList[$gradeAndWeekKey]['schedule_time_json'], true);
                                $newScheduleArr = $groupTime['times'];
                                if($oldScheduleArr) {
                                    foreach($oldScheduleArr as $key => $value) {
                                        if(isset($newScheduleArr[$key])) {
                                            // 判断是否删除
                                            if(isset($value['sign_interval'])) {
                                                $newScheduleArr[$key]['sign_interval'] = $value['sign_interval'];
                                            }
                                            if(isset($value['refresh'])) {
                                                $newScheduleArr[$key]['refresh'] = $value['refresh'];
                                            }
                                        }
                                    }
                                    $thisWeekData['schedule_time_json'] = json_encode($newScheduleArr, JSON_UNESCAPED_UNICODE);
                                }

                                $this->db->update(ClassesModel::$scheduleTable, $thisWeekData, "id='{$scheduleList[$gradeAndWeekKey]['id']}'");
                            } else {
                                $thisWeekData['createtime'] = $thisWeekData['updatetime'];
                                $this->db->insert(ClassesModel::$scheduleTable, $thisWeekData);
                            }
                        }
                    }
               }      
           }
        }
    }
    // 课表接口，更新课程表课程数据
    private function __update_schedule_lesson_data($schoolInfo, $campusInfo, $scheduleList, $scheduleLessonList, $teacherList, $classList, $roomList, $isThisWeek, $scheduApiData){
      
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($schoolInfo['id'], $campusInfo['id']);
        $tmpScheduleArr = array();
        if($onlyOneSchedule == false) {
            $tmpScheduleArr = $this->classesModel->get_daily_grade_schdedule($schoolInfo['id'], $campusInfo['id']);
            // echo '<pre>';var_export($tmpScheduleArr);exit;
        } else {
            $scheduleKey = $schoolInfo['id']. $isThisWeek;
            $scheduleId = $scheduleList[$scheduleKey]['id'];
        }

        $insertLessonBatch = $updateLessonBatch = array();
        if($scheduApiData) {
            // 遍历数据
            foreach($scheduApiData as $lesson){
                if(isset($classList[$lesson['qualifiedClassID']])) {
                    $lessonData['school_id'] = $schoolInfo['id'];
                    $lessonData['campus_id'] = $campusInfo['id'];       // 设置校区id
                    $lessonData['class_id'] = isset($classList[$lesson['qualifiedClassID']]) ? $classList[$lesson['qualifiedClassID']]['id'] : 0;
                    // 如果是年级不同作息，获取年级模板id
                    if($onlyOneSchedule == false) {
                        if(!isset($classList[$lesson['qualifiedClassID']])) {
                            // 找不到对应的班级，不插入
                            continue;
                        }
                        $gradeId = $classList[$lesson['qualifiedClassID']]['grade_id'];
                        $index = $schoolInfo['id'] . '_' . $campusInfo['id'] . '_' . $gradeId . '_' . $lesson['weekDay'];

                        if(!isset($tmpScheduleArr[$index])) {
                            continue;
                        }
                        $scheduleId = $tmpScheduleArr[$index]['id'];

                        // echo '<pre>';var_export($scheduleId);exit;
                    }

                    $lessonData['schedule_id'] = $scheduleId;
                    $lessonData['schedule_week_index'] = $lesson['weekDay'];
                    $lessonData['schedule_class_index'] = $lesson['timeslot'];
                    $lessonData['schedule_lesson_id'] = $scheduleId . '_' . $lessonData['class_id']. '_' . $lesson['weekDay']. '_' . $lesson['timeslot'];
                    $lessonData['schedule_lesson'] = $lesson['subjectName'];
                    $lessonData['is_delete'] = 0;
                    // 如果有授课老师
                    $lessonData['schedule_teacher'] = count($lesson['teachers']) && isset($teacherList[$lesson['teachers'][0]['teacherEID']]) ? $teacherList[$lesson['teachers'][0]['teacherEID']]['id'] : 0;
                    // if(count($lesson['teachers'])) $lessonData['schedule_teacher'] = $teacherList[$lesson['teachers'][0]['teacherEID']]['id'];
                    // 如果有课室
                    $lessonData['schedule_room_id'] = isset($roomList[$lesson['locationID']]) && $lesson['locationID'] ? $roomList[$lesson['locationID']]['id'] : 0;
                    // $lessonData['schedule_room_id'] = $lesson['locationID'] ? $roomList[$lesson['locationID']]['id'] : 0;
                    $lessonData['updatetime'] = date("Y-m-d H:i:s");
                    if(isset($scheduleLessonList[$lessonData['schedule_lesson_id']])) {
                        $updateLessonBatch[] = $lessonData;
                    } else {
                        $lessonData['createtime'] = $lessonData['updatetime'];
                        $insertLessonBatch[] = $lessonData;
                    }
                }
            }
        }
        // echo '<pre>';var_export($insertLessonBatch);exit;
        if(count($insertLessonBatch)) $this->db->insert_batch(ClassesModel::$scheduleLessonTable, $insertLessonBatch);
        if(count($updateLessonBatch)) $this->db->update_batch(ClassesModel::$scheduleLessonTable, $updateLessonBatch, "schedule_lesson_id");
    }
    // 同步考试数据
    private function _update_hzy_exam_data($schoolInfo, $campusInfo) {
        // 获取考试列表
        $result = $this->haozhuanyev2->get_school_exam($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] !== 'success') {
            if(!isset($result['errorMessage'])){
                $result['errorMessage'] = '获取考试数据失败';
            } else {
                $result['errorMessage'] .= '获取考试数据失败:';
            }
            // 当没部署这接口时，跳过
            // throw new Exception($result['errorMessage']);
            return;
        }
        $apiData = $result['result'];
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(DataModel::$examTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
        $this->db->update(DataModel::$examRoomTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
        $this->db->update(DataModel::$examRoomDetailTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
        // 获取本校全部考试
        $params['schoolId'] = $schoolInfo['id'];
        $params['selectAll'] = 1;
        $examParams['field'] = 'id, x_exam_id';
        $examList = $this->dataModel->get_exam_list(array_merge($params, $examParams));
        $examList = array_value_to_key($examList, 'x_exam_id');
        // 获取本校全部考场
        $roomParams['field'] = 'id, x_room_id';
        $roomList = $this->dataModel->get_exam_room_list(array_merge($params, $roomParams));
        $roomList = array_value_to_key($roomList, 'x_room_id');
        // 获取本校全部考场详情
        $detailParams['field'] = 'id, x_room_id, x_detail_id';
        $detailList = $this->dataModel->get_all_exam_room_detail_list(array_merge($params, $detailParams));
        $detailList = array_value_to_key($detailList, 'x_room_id,x_detail_id');
        $examData = array();
        $roomData = array();
        $detailData = array();
        $updateExamBatch = array();
        $insertExamBatch = array();
        $updateRoomBatch = array();
        $insertRoomBatch = array();
        $updateDetailBatch = array();
        $insertDetailBatch = array();
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolInfo['id'];
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'x_grade_id');
        // 获取本校全部课室
        $classRoomParams['schoolId'] = $schoolInfo['id'];
        $calssRoomList = $this->classesModel->get_classroom_list($classRoomParams);
        $calssRoomList = array_value_to_key($calssRoomList, 'x_classroom_id');
        // 获取本校全部科目
        $lessonParams['schoolId'] = $schoolInfo['id'];
        $lessonList = $this->schoolModel->get_lesson_list($lessonParams);
        $lessonList = array_value_to_key($lessonList, 'x_lesson_id');
        // 获取本校全部学生
        $studentParams['schoolId'] = $schoolInfo['id'];
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'x_student_id');
        // 获取本校全部老师
        $params['schoolId'] = $schoolInfo['id'];
        $teacherList = $this->schoolModel->get_teacher_list($params);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');

        // 获取接口所有考试列表
        foreach($apiData as $exam) {
            $xExamId = $exam['examID'];
            // 考试数据入库
            $examData['x_exam_id'] = $xExamId;
            $examData['school_id'] = $schoolInfo['id'];
            $examData['campus_id'] = $campusInfo['id'];
            $examData['title'] = $exam['title'];
            $examData['is_delete'] = 0;
            $examData['updatetime'] = date('Y-m-d H:i:s');
            // 更新还是新增
            if(isset($examList[$xExamId])){
                $updateExamBatch[] = $examData;
            } else {
                $examData['createtime'] = $examData['updatetime'];
                $insertExamBatch[] = $examData;
            }
            foreach($exam['exam'] as $room){
                $xRoomId = $room['id'];
                // 考场数据入库
                $roomData['x_room_id'] = $xRoomId;
                $roomData['x_exam_id'] = $xExamId;
                $roomData['school_id'] = $schoolInfo['id'];
                $roomData['campus_id'] = $campusInfo['id'];
                $roomData['grade_id'] = isset($gradeList[$room['gradeID']]) ? $gradeList[$room['gradeID']]['id'] : 0;
                $roomData['lesson_id'] = isset($lessonList[$room['subjectID']]) ? $lessonList[$room['subjectID']]['id'] : 0;
                $roomData['type'] = $room['type'];
                $roomData['day'] = $room['time']['day'];
                $roomData['begin'] = $room['time']['begin'];
                $roomData['end'] = $room['time']['end'];
                $roomData['timeslot'] = $room['time']['timeslot'];
                $roomData['part_of_day'] = $room['partOfDay'];
                // 通过xid获取id
                $teacherIdArr = array();
                $studentIdArr = array();
                foreach($room['outsideTeacher'] as $teacherXid){
                    $teacherIdArr[] = isset($teacherList[$teacherXid]) ? $teacherList[$teacherXid]['id'] : 0;
                }
                foreach($room['freeStudents'] as $studentXid){
                    $studentIdArr[] = isset($studentList[$studentXid]) ? $studentList[$studentXid]['id'] : 0;
                }
                // 拼凑用户id数组成字符串
                $outsideTeacherStr = implode(',', $teacherIdArr);
                $freeStudentsStr = implode(',', $studentIdArr);
                $roomData['outside_teachers'] = $outsideTeacherStr;
                $roomData['free_students'] = $freeStudentsStr;
                $roomData['is_delete'] = 0;
                $roomData['updatetime'] = date('Y-m-d H:i:s');
                if(isset($roomList[$xRoomId])){
                    $updateRoomBatch[] = $roomData;
                } else {
                    $roomData['createtime'] = $roomData['updatetime'];
                    $insertRoomBatch[] = $roomData;
                }
                if(isset($room['examRooms'])){
                    foreach($room['examRooms'] as $detail){
                        // 考场详情数据入库
                        $detailData['x_room_id'] = $xRoomId;
                        $detailData['x_detail_id'] = $detail['roomID'];
                        $detailData['school_id'] = $schoolInfo['id'];
                        $detailData['campus_id'] = $campusInfo['id'];
                        $detailData['location_id'] = isset($calssRoomList[$detail['locationID']]) ? $calssRoomList[$detail['locationID']]['id'] : 0;
                        $detailData['room_no'] = $detail['roomNO'];
                        $detailData['room_name'] = $detail['roomName'];
                        $detailData['student_capacity'] = $detail['studentCapacity'];
                        // 通过学生xid获取id
                        foreach($detail['students'] as $key => $student){
                            $studentXid = $student['userID'];
                            $detail['students'][$key]['userID'] = isset($studentList[$studentXid]) ? $studentList[$studentXid]['id'] : 0;
                        }  
                        // students数组转换成json字符串
                        $detailData['students'] = json_encode($detail['students']);
                        // 拼凑用户id数组成字符串
                        $teacherIdArr = array();
                        foreach($detail['insideTeachers'] as $teacherXid){
                            $teacherIdArr[] = isset($teacherList[$teacherXid]) ? $teacherList[$teacherXid]['id'] : 0;
                        }
                        $insideTeacherStr = implode(',', $teacherIdArr);
                        $detailData['inside_teachers'] = $insideTeacherStr;
                        $detailData['is_delete'] = 0;
                        $detailData['updatetime'] = date('Y-m-d H:i:s');

                        $uniqueId = $xRoomId . $detail['roomID'];
                        if(isset($detailList[$uniqueId])){
                            $updateDetailBatch[] = $detailData;
                        } else {
                            $detailData['createtime'] = $detailData['updatetime'];
                            $insertDetailBatch[] = $detailData;
                        }
                    }
                }
            }
        }
        if(count($insertExamBatch)) $this->db->insert_batch(DataModel::$examTable, $insertExamBatch);
        if(count($updateExamBatch)) $this->db->update_batch(DataModel::$examTable, $updateExamBatch, "x_exam_id");
        if(count($insertRoomBatch)) $this->db->insert_batch(DataModel::$examRoomTable, $insertRoomBatch);
        if(count($updateRoomBatch)) $this->db->update_batch(DataModel::$examRoomTable, $updateRoomBatch, "x_room_id");
        if(count($insertDetailBatch)) $this->db->insert_batch(DataModel::$examRoomDetailTable, $insertDetailBatch);
        if(count($updateDetailBatch)) {
            foreach($updateDetailBatch as $updateBatch) {
                $this->db->where(array(
                    'x_room_id' => $updateBatch['x_room_id'],
                    'x_detail_id' => $updateBatch['x_detail_id'],
                ));
                $this->db->update(DataModel::$examRoomDetailTable, $updateBatch);
            }  
        }
        // 设置exam_id
        if(count($insertRoomBatch)){
            foreach($insertRoomBatch as $room){
                $xExamId = $room['x_exam_id'];
                $exam = $this->dataModel->get_exam_info(array(
                    'xid' => $xExamId,
                    'field' => 'id'
                ));
                $this->db->where(array(
                    'x_room_id' => $room['x_room_id']
                ));
                $this->db->update(DataModel::$examRoomTable, array(
                    'exam_id' => $exam['id']
                ));
            }
        }
        
        // 设置room_id
        if(count($insertDetailBatch)){
            foreach($insertDetailBatch as $detail){
                $xRoomId = $detail['x_room_id'];
                $room = $this->dataModel->get_exam_room_info(array(
                    'xid' => $xRoomId,
                    'field' => 'id'
                ));
                $this->db->where(array(
                    'x_room_id' => $detail['x_room_id'],
                    'x_detail_id' => $detail['x_detail_id'],
                ));
                $this->db->update(DataModel::$examRoomDetailTable, array(
                    'room_id' => $room['id']
                ));
            }
        }
    }
    // 同步班主任执教关系
    private function _update_hzy_coach_master_data($schoolInfo, $campusInfo) {
        // 获取全部班主任数据
        $masterCoachList = $this->staffModel->get_coach_by_school($schoolInfo['id'], $campusInfo['id'], COACH_TYPE_MASTER);
        // 使用school_id,campus_id,coach_type,teacher_id,class_ids作为键值
        $masterCoachList = array_value_to_key_with_underline($masterCoachList, 'school_id,campus_id,coach_type,teacher_id,class_ids');
     
        // 将全部班主任数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $coachTypeMaster = COACH_TYPE_MASTER;
        $this->db->update(StaffModel::$coachTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `campus_id`='{$campusInfo['id']}' AND `coach_type` = '{$coachTypeMaster}'");
        // 获取本校全部老师
        $teacherParams['schoolId'] = $schoolInfo['id'];
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');
        // 获取本校全部班级
        $classParams['schoolId'] = $schoolInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'x_class_id');
        //获取全部行政班信息接口
        $insertCoachBatch = $updateCoachBatch = array();
        $result = $this->haozhuanyev2->get_school_classes($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取班级接口失败');
        $apiData = $result['result']['classes'];
        foreach($apiData as $item) {
            $coachData = array();
            if(isset($item['classTeacher']) && $item['classTeacher'] && isset($item['classTeacher']['teacherEID']) && isset($teacherList[$item['classTeacher']['teacherEID']]) 
            && isset($classList[$item['qualifiedClassID']])) {
                $coachData['school_id'] = $schoolInfo['id'];
                $coachData['campus_id'] = $campusInfo['id']; // 设置校区id
                $coachData['class_ids'] = $classList[$item['qualifiedClassID']]['id'];
                $coachData['teacher_id'] = $teacherList[$item['classTeacher']['teacherEID']]['id'];
                $coachData['coach_type'] = COACH_TYPE_MASTER;
                $coachData['is_delete'] = 0;
                $coachData['updatetime'] = date("Y-m-d H:i:s");

                $keyIndexArr = array($coachData['school_id'], $coachData['campus_id'], $coachData['coach_type'], $coachData['teacher_id'], $coachData['class_ids']);
                $keyIndexStr = implode('_', $keyIndexArr);
                if(isset($masterCoachList[$keyIndexStr])) {
                    $coachData['id'] = $masterCoachList[$keyIndexStr]['id'];
                    $updateCoachBatch[] = $coachData;
                } else {
                    $coachData['createtime'] = date("Y-m-d H:i:s");
                    $insertCoachBatch[] = $coachData;
                }
            }
        }
        // 获取全部教学班接口
        $result = $this->haozhuanyev2->get_school_teaching_classes($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取教学班接口失败');
        $apiData = $result['result']['teachingClasses'];
        foreach($apiData as $item) {
            $coachData = array();
            if(isset($item['classTeacher']) && $item['classTeacher'] && isset($item['classTeacher']['teacherEID']) && isset($teacherList[$item['classTeacher']['teacherEID']]) 
            && isset($classList[$item['qualifiedClassID']])) {
                $coachData['school_id'] = $schoolInfo['id'];
                $coachData['campus_id'] = $campusInfo['id']; // 设置校区id
                $coachData['class_ids'] = $classList[$item['qualifiedClassID']]['id'];
                $coachData['teacher_id'] = $teacherList[$item['classTeacher']['teacherEID']]['id'];
                $coachData['coach_type'] = COACH_TYPE_MASTER;
                $coachData['is_delete'] = 0;
                $coachData['updatetime'] = date("Y-m-d H:i:s"); 

                $keyIndexArr = array($coachData['school_id'], $coachData['campus_id'], $coachData['coach_type'], $coachData['teacher_id'], $coachData['class_ids']);
                $keyIndexStr = implode('_', $keyIndexArr);
                if(isset($masterCoachList[$keyIndexStr])) {
                    $coachData['id'] = $masterCoachList[$keyIndexStr]['id'];
                    $updateCoachBatch[] = $coachData;
                } else {
                    $coachData['createtime'] = date("Y-m-d H:i:s");
                    $insertCoachBatch[] = $coachData;
                }
            }
        }
        
        if(count($insertCoachBatch)) $this->db->insert_batch(StaffModel::$coachTable, $insertCoachBatch);
        if(count($updateCoachBatch)) $this->db->update_batch(StaffModel::$coachTable, $updateCoachBatch, "id");
    }
    // 同步年级管理员执教关系
    private function _update_hzy_coach_grade_admin_data($schoolInfo, $campusInfo) {
        // 获取全部年级管理员数据
        $gradeCoachList = $this->staffModel->get_coach_by_school($schoolInfo['id'], $campusInfo['id'], COACH_TYPE_GRADE_ADMIN);
        // 使用school_id,campus_id,coach_type,teacher_id,grade_id作为键值
        $gradeCoachList = array_value_to_key_with_underline($gradeCoachList, 'school_id,campus_id,coach_type,teacher_id,grade_id');

        // 将全部年级管理员数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $coachTypeGrade = COACH_TYPE_GRADE_ADMIN;
        $this->db->update(StaffModel::$coachTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `campus_id`='{$campusInfo['id']}' AND `coach_type` = '{$coachTypeGrade}'");
        // 获取本校全部老师
        $teacherParams['schoolId'] = $schoolInfo['id'];
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolInfo['id'];
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'x_grade_id');
        //获取全部年级信息接口
        $insertCoachBatch = $updateCoachBatch = array();
        $result = $this->haozhuanyev2->get_school_grades($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取年级接口失败');
        $apiData = $result['result']['grades'];
        // 获取教师角色-年级管理员
        $gradeAdminRoleIdArr = $this->staffModel->get_role_id_by_name($schoolInfo['id'], '年级管理员');
        foreach($apiData as $item) {
            $coachData = array();
            if(isset($item['gradeAdmins']) && $item['gradeAdmins']) {
                foreach($item['gradeAdmins'] as $itemGradeAdmin) {
                    if(isset($teacherList[$itemGradeAdmin['teacherEID']])) {
                        $coachData['school_id'] = $schoolInfo['id'];
                        $coachData['campus_id'] = $campusInfo['id']; // 设置校区id
                        $coachData['grade_id'] = $gradeList[$item['gradeID']]['id'];
                        $coachData['teacher_id'] = $teacherList[$itemGradeAdmin['teacherEID']]['id'];
                        $coachData['coach_type'] = COACH_TYPE_GRADE_ADMIN;
                        $coachData['is_delete'] = 0;
                        $coachData['updatetime'] = date("Y-m-d H:i:s");
        
                        $keyIndexArr = array($coachData['school_id'], $coachData['campus_id'], $coachData['coach_type'], $coachData['teacher_id'], $coachData['grade_id']);
                        $keyIndexStr = implode('_', $keyIndexArr);
                        if(isset($gradeCoachList[$keyIndexStr])) {
                            $coachData['id'] = $gradeCoachList[$keyIndexStr]['id'];
                            $updateCoachBatch[] = $coachData;
                        } else {
                            $coachData['createtime'] = date("Y-m-d H:i:s");
                            $insertCoachBatch[] = $coachData;
                        }

                        // 插入教师角色
                        if(isset($gradeAdminRoleIdArr['id']) && empty($teacherList[$itemGradeAdmin['teacherEID']]['role_id_set'])) {
                            $teacherId = $teacherList[$itemGradeAdmin['teacherEID']]['id'];
                            $this->db->update(SchoolModel::$schoolUserTable, array('role_id_set'=> $gradeAdminRoleIdArr['id']), "id='{$teacherId}'");
                        }
                    } 
                }
            }
        }
        // echo '<pre>';echo'---insert---';var_export($insertCoachBatch);
        // echo '<pre>';echo'---update---';var_export($updateCoachBatch);
        if(count($insertCoachBatch)) $this->db->insert_batch(StaffModel::$coachTable, $insertCoachBatch);
        if(count($updateCoachBatch)) $this->db->update_batch(StaffModel::$coachTable, $updateCoachBatch, "id");
    }
    // 同步学校管理员执教关系
    private function _update_hzy_coach_school_admin_data($schoolInfo, $campusInfo) {
        // 获取全部年级管理员数据
        $gradeCoachList = $this->staffModel->get_coach_by_school($schoolInfo['id'], $campusInfo['id'], COACH_TYPE_SCHOOL_ADMIN);
        // 使用school_id,campus_id,coach_type,teacher_id作为键值
        $gradeCoachList = array_value_to_key_with_underline($gradeCoachList, 'school_id,campus_id,coach_type,teacher_id');

        // 将全部学校管理员执教关系数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $coachTypeSchoolAdmin = COACH_TYPE_SCHOOL_ADMIN;
        $this->db->update(StaffModel::$coachTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `campus_id`='{$campusInfo['id']}' AND `coach_type` = '{$coachTypeSchoolAdmin}'");
        // 获取本校全部老师
        $teacherParams['schoolId'] = $schoolInfo['id'];
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');
        //获取全部学校管理员信息接口
        $insertCoachBatch = $updateCoachBatch = array();
        $result = $this->haozhuanyev2->get_school_admins($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取学校管理员接口失败');
        if(isset($result['result']['schoolInfo']['schoolAdmins'])) {
            $apiData = $result['result']['schoolInfo']['schoolAdmins'];
        }
        if(empty($apiData)) {
            $apiData = array();
        }

        // 获取教师角色-学校管理员
        $schoolAdminRoleIdArr = $this->staffModel->get_role_id_by_name($schoolInfo['id'], '学校管理员');
        foreach($apiData as $item) {
            $coachData = array();
            if(isset($teacherList[$item['teacherEID']])) {
                $coachData['school_id'] = $schoolInfo['id'];
                $coachData['campus_id'] = $campusInfo['id']; // 设置校区id
                $coachData['teacher_id'] = $teacherList[$item['teacherEID']]['id'];
                $coachData['coach_type'] = COACH_TYPE_SCHOOL_ADMIN;
                $coachData['is_delete'] = 0;
                $coachData['updatetime'] = date("Y-m-d H:i:s");

                $keyIndexArr = array($coachData['school_id'], $coachData['campus_id'], $coachData['coach_type'], $coachData['teacher_id']);
                $keyIndexStr = implode('_', $keyIndexArr);
                if(isset($gradeCoachList[$keyIndexStr])) {
                    $coachData['id'] = $gradeCoachList[$keyIndexStr]['id'];
                    $updateCoachBatch[] = $coachData;
                } else {
                    $coachData['createtime'] = date("Y-m-d H:i:s");
                    $insertCoachBatch[] = $coachData;
                }

                // 插入教师角色
                if(isset($schoolAdminRoleIdArr['id']) && empty($teacherList[$item['teacherEID']]['role_id_set'])) {
                    $teacherId = $teacherList[$item['teacherEID']]['id'];
                    $this->db->update(SchoolModel::$schoolUserTable, array('role_id_set'=> $schoolAdminRoleIdArr['id']), "id='{$teacherId}'");
                }
            }
        }
        // echo '<pre>';echo'---insert---';var_export($insertCoachBatch);
        // echo '<pre>';echo'---update---';var_export($updateCoachBatch);exit;
        if(count($insertCoachBatch)) $this->db->insert_batch(StaffModel::$coachTable, $insertCoachBatch);
        if(count($updateCoachBatch)) $this->db->update_batch(StaffModel::$coachTable, $updateCoachBatch, "id");
    }
    // 同步教师执教关系
    private function _update_hzy_coach_teacher_data($schoolInfo, $campusInfo) {
        // 获取全部班主任数据
        $teacherCoachList = $this->staffModel->get_coach_by_school($schoolInfo['id'], $campusInfo['id'], COACH_TYPE_TEACHER);
        // 使用school_id,campus_id,coach_type,teacher_id,class_ids,subject_ids作为键值
        $teacherCoachList = array_value_to_key_with_underline($teacherCoachList, 'school_id,campus_id,coach_type,teacher_id,class_ids,subject_ids');
        // 将全部任课教师数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $coachTypeTeacher = COACH_TYPE_TEACHER;
        $this->db->update(StaffModel::$coachTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `campus_id`='{$campusInfo['id']}' AND `coach_type` = '{$coachTypeTeacher}'");
        // 获取本校全部老师
        $teacherParams['schoolId'] = $schoolInfo['id'];
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');
        // 获取本校全部班级
        $classParams['schoolId'] = $schoolInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'x_class_id');
        // 获取本校全部科目
        $subjectParams['isDelete'] = 0;
        $subjectParams['schoolId'] = $schoolInfo['id'];
        $subjectList = $this->schoolModel->get_lesson_list($subjectParams);
        $subjectList = array_value_to_key($subjectList, 'x_lesson_id');
        //获取全部行政班信息接口
        $insertCoachBatch = $updateCoachBatch = array();
        $result = $this->haozhuanyev2->get_school_coach($schoolInfo['school_x_id']);
        if(!isset($result['status']) || $result['status'] != 'success') throw new Exception($result['errorMessage'] ? $result['errorMessage'] : '获取任课教师接口失败');
        $apiData = isset($result['result']['courseTeachings']) ? $result['result']['courseTeachings'] : array();
        foreach($apiData as $item) {
            if(isset($item['subjectID']) && $item['subjectID'] && isset($subjectList[$item['subjectID']])) {
                foreach($item['teachers'] as $teacher) {
                    $coachData = array();
                    if(isset($teacher['teacherEID']) && $teacher['teacherEID'] && isset($teacherList[$teacher['teacherEID']])) {
                        $coachData['school_id'] = $schoolInfo['id'];
                        $coachData['campus_id'] = $campusInfo['id']; // 设置校区id
                        $coachData['class_ids'] = $classList[$item['qualifiedClassID']]['id'];
                        $coachData['teacher_id'] = $teacherList[$teacher['teacherEID']]['id'];
                        $coachData['subject_ids'] = $subjectList[$item['subjectID']]['id'];
                        $coachData['coach_type'] = COACH_TYPE_TEACHER;
                        $coachData['is_delete'] = 0;
                        $coachData['updatetime'] = date("Y-m-d H:i:s");
        
                        $keyIndexArr = array($coachData['school_id'], $coachData['campus_id'], $coachData['coach_type'], $coachData['teacher_id'], $coachData['class_ids'], $coachData['subject_ids']);
                        $keyIndexStr = implode('_', $keyIndexArr);
                        if(isset($teacherCoachList[$keyIndexStr])) {
                            $coachData['id'] = $teacherCoachList[$keyIndexStr]['id'];
                            $updateCoachBatch[] = $coachData;
                        } else {
                            $coachData['createtime'] = date("Y-m-d H:i:s");
                            $insertCoachBatch[] = $coachData;
                        }
                    }
                }
            }
        }
        // echo '<pre>';echo'---insert---';var_export($insertCoachBatch);
        // echo '<pre>';echo'---update---';var_export($updateCoachBatch);
        // exit;
        if(count($insertCoachBatch)) $this->db->insert_batch(StaffModel::$coachTable, $insertCoachBatch);
        if(count($updateCoachBatch)) $this->db->update_batch(StaffModel::$coachTable, $updateCoachBatch, "id");
    }
    // 把教师角色为空的设置‘任课教师’角色
    private function _update_hzy_coach_teacher_role_empty_data($schoolInfo) {
        // 获取教师角色-学校管理员
        $teacherRoleIdArr = $this->staffModel->get_role_id_by_name($schoolInfo['id'], '任课教师');
        if(isset($teacherRoleIdArr['id'])) {
            $this->db->update(SchoolModel::$schoolUserTable, array('role_id_set'=> $teacherRoleIdArr['id']), "`school_id` = '{$schoolInfo['id']}' AND role_id_set='' AND `user_type`=" . USER_TYPE_TEACHER);
        }
    }
    // 多年级作息，又存在选修班的情况，添加该选修年级的作息时间（默认获取第一个作息）
    private function _update_hzy_elective_grade_schedule_data($schoolInfo, $campusInfo) {
        // 判断是否年级不同作息
        $isOnlyOneSchedule = $this->classesModel->check_is_only_one_schedule($schoolInfo['id'], $campusInfo['id']);
        if($isOnlyOneSchedule) {
            return;
        }
        // 获取学校选修年级
        $electiveGradeInfo = $this->classesModel->get_elective_grade_info_list($schoolInfo['id'], $campusInfo['id']);
        if($electiveGradeInfo) {
            // 获取学校第一个年级的作息
            $firstScheduleInfo = $this->classesModel->get_campus_schedule($campusInfo['id']);
            // 判断该作息是否存在
            $scheduleInfo = $this->classesModel->get_one_daily_grade_schdedule_by_week($schoolInfo['id'], $campusInfo['id'], $electiveGradeInfo['id'], 1, 1);
            // 去掉id键值
            unset($firstScheduleInfo['id']);

            if($firstScheduleInfo['schedule_week_days'] == 6) {
                $week = '1,2,3,4,5,6';
            } else if($firstScheduleInfo['schedule_week_days'] == 7) {
                $week = '1,2,3,4,5,6,7';
            } else {
                $week = '1,2,3,4,5';
            }
            $firstScheduleInfo['week'] = $week;
            $firstScheduleInfo['grade_id'] = $electiveGradeInfo['id'];
            $data = $firstScheduleInfo;
            if($scheduleInfo) {
                // 更新
                $this->db->update(ClassesModel::$scheduleTable, $data, "id={$scheduleInfo['id']}");
            } else {
                // 插入
                $this->db->insert(ClassesModel::$scheduleTable, $data);
            }
        }
       
    }

}
